package com.bzkj.basicinfo.service.impl.ncc;

import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.bzkj.basicinfo.domain.ncc.NccBasicStoStock;
import com.bzkj.basicinfo.domain.ncc.dto.NccBasicStoStockDto;
import com.bzkj.basicinfo.domain.ncc.erp.StoStockBean;
import com.bzkj.basicinfo.mapper.NccBasicStoStockMapper;
import com.bzkj.basicinfo.service.ncc.NccBasicStoStockService;
import com.bzkj.basicinfo.utils.DataBatchProcessorUtil;
import com.bzkj.basicinfo.utils.HttpClientUtils;
import com.bzkj.basicinfo.utils.NccBasicUtil;
import com.bzkj.basicinfo.utils.UniqueIdentifierGenerator;
import com.bzkj.common.core.domain.AjaxResult;
import com.bzkj.common.core.domain.R;
import com.bzkj.common.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;

/**
 * 仓库信息：8
 */
@Slf4j
@Service("nccJobStoStockService")
public class NccBasicStoStockServiceImpl implements NccBasicStoStockService {
    @Autowired
    private NccBasicStoStockMapper nccBasicStoStockMapper;
    @Autowired
    private NccBasicUtil nccBasicUtil;
    @Value("${ncc.baseUrl}")
    private String url;

    @Value("${ncc.basicInfoUrl}")
    private String basicInfoUrl;

    @Value("${ncc.sourceSystem}")
    private static String sourceSystem;

    @Value("${ncc.targetSystem}")
    private static String targetSystem;

    @Value("${ncc.serviceName}")
    private static String serviceName;

    @Value("${ncc.contentType}")
    private static String contentType;

    @Value("${pk_org.code}")
    private Integer pkOrgCode;

    @Autowired
    private UniqueIdentifierGenerator uniq;

    @Override
    public void updateNccBasicStoStockJob(String all) {
        if ("all".equals(all)) {
            nccBasicUtil.ncc(8, pkOrgCode);
        } else {
            HttpResponse response = methodExecute(8);
            if (response.isOk()) {
                String responseBody = response.body();
                JSONObject entries = JSONUtil.parseObj(responseBody);
                JSONArray dataArray = entries.getJSONArray("data");
                List<NccBasicStoStock> basicStoStocks = dataArray.toList(NccBasicStoStock.class);
                for (NccBasicStoStock basicStoStock : basicStoStocks) {
                    NccBasicStoStock basicStoStock1 = nccBasicStoStockMapper.queryNccBasicStoStock(basicStoStock.getCode());
                    if (basicStoStock1 != null) {
                        nccBasicStoStockMapper.updateNccBasicStoStock(basicStoStock);
                    } else {
                        nccBasicStoStockMapper.insertNccBasicStoStock(basicStoStock);
                    }
                }
            }
        }
    }

    /**
     * 根据pkStoDoc修改仓库状态
     *
     * @Author wangzhichao
     * @Date 2024/12/05 17:06:14
     * @Param state 状态
     * @Param pkStoDoc 主键
     */
    @Override
    public AjaxResult nccBasicStoStockEnableState(String state, String pkStoDoc) {
        try {
            int i = nccBasicStoStockMapper.nccBasicStoStockEnableState(state, pkStoDoc);
            return i > 0 ? AjaxResult.success("修改成功") : AjaxResult.error("未找到指定数据");
        } catch (Exception e) {
            log.error("修改失败:{}", e);
            return AjaxResult.error("修改失败");
        }
    }

    /**
     * 根据pK_STORDOC修改仓库信息
     *
     * @Author wangzhichao
     * @Date 2024/12/06 08:32:56
     * @Param entity
     */
    @Override
    public AjaxResult nccBasicStoStockUpdate(NccBasicStoStock entity) {
        try {
            NccBasicStoStock stock = nccBasicStoStockMapper.queryNccBasicStoStock(entity.getCode());
            if (Objects.isNull(stock)) {
                int i = nccBasicStoStockMapper.nccBasicStoStockUpdate(entity);
                return i > 0 ? AjaxResult.success("修改成功") : AjaxResult.error("未找到指定数据");
            } else {
                if (stock.getpK_STORDOC().equals(entity.getpK_STORDOC())) {
                    int i = nccBasicStoStockMapper.nccBasicStoStockUpdate(entity);
                    return AjaxResult.success("修改成功");
                } else {
                    return AjaxResult.error("仓库代码重复");
                }
            }

        } catch (Exception e) {
            log.error("修改失败：{}", e);
            return AjaxResult.error("修改失败");
        }
    }

    /**
     * 根据条件分页查询仓库信息
     *
     * @Author wangzhichao
     * @Date 2024/12/06 08:57:38
     * @Param dto 查询条件
     * @Param page 分页条件
     */
    @Override
    public List<NccBasicStoStock> findNccBasicStoStockData(NccBasicStoStockDto dto) {
        List<NccBasicStoStock> list = nccBasicStoStockMapper.findNccBasicStoStockData(dto);
        return list;
    }

    /**
     * 保存仓库信息
     *
     * @Author wangzhichao
     * @Date 2024/12/06 09:30:54
     * @Param entity
     */
    @Override
    public AjaxResult nccBasicStoStockSave(NccBasicStoStock entity) {
        try {
            NccBasicStoStock stock = nccBasicStoStockMapper.queryNccBasicStoStock(entity.getCode());
            if (Objects.isNull(stock)) {
                String userName = SecurityUtils.getLoginUser().getUser().getUserName();
                entity.setCreationtime(new Date());
                entity.setCreator(userName);
                entity.setModifier(userName);
                entity.setpK_GROUP("0001A1100000000021CH");
                //生成仓库唯一标识
                synchronized (this) {
                    String pkStoDoc = "WMS" + uniq.generateUniqueIdentifier();
                    entity.setpK_STORDOC(pkStoDoc);
                }
                nccBasicStoStockMapper.insertNccBasicStoStock(entity);
                return AjaxResult.success("保存成功");
            } else {
                return AjaxResult.error("仓库代码重复");
            }
        } catch (Exception e) {
            log.error("保存失败:{}", e);
            return AjaxResult.error("保存失败");
        }
    }

    @Override
    public R findNccBasicStoStockAll() {
        List<NccBasicStoStock> list = nccBasicStoStockMapper.findNccBasicStoStockAll();
        return R.ok(list);
    }

    @Override
    public List<String> findNccBasicStoStockName(String name) {
        return nccBasicStoStockMapper.findNccBasicStoStockName(name);
    }

    @Autowired
    private HttpClientUtils hcu;

    /**
     * 定时同步当天仓库信息
     *
     * @return
     */
    @Override
    public R jobMethodExecute(Boolean flag) {
        HashMap<String, String> searchDate = DataBatchProcessorUtil.getSearchDate(flag);

        // 查询当前数据
        HttpResponse response = hcu.methodExecute(searchDate.get("startTimeStr"), searchDate.get("endTimeStr"), 8, pkOrgCode);
        com.alibaba.fastjson2.JSONObject jsonNode = JSON.parseObject(response.body());
        // 收集rep系统数据
        List<StoStockBean> list = jsonNode.getJSONArray("data").toJavaList(StoStockBean.class);
        if (!list.isEmpty()) {
            extracted(list);
        }

        return R.ok("同步成功");
    }

    /**
     * 批量更新或者插入
     *
     * @Date 2024/12/11 14:17:12
     * @Param list
     */
    @Transactional(rollbackFor = Exception.class)
    public void extracted(List<StoStockBean> list) {
        for (StoStockBean stoStockBean : list) {
            nccBasicStoStockMapper.insertOrUpdate(stoStockBean);
        }
    }

    /**
     * 公有方法抽取
     *
     * @param i
     * @return
     */
    public HttpResponse methodExecute(Integer i) {
        //        String url = NccHttpUtils.getUrl();
        HashMap<String, Object> hashMap = new HashMap<>();
        // 定义时间格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        // 获取昨天的日期
        LocalDate yesterday = LocalDate.now().minusDays(1);
        // 昨天的00:00
        LocalDateTime startOfYesterday = yesterday.atStartOfDay();
        String startOfYesterdayStr = startOfYesterday.format(formatter);
        // 昨天的23:59:59
        LocalDateTime endOfYesterday = yesterday.atTime(23, 59, 59);
        String endOfYesterdayStr = endOfYesterday.format(formatter);
        //        添加post请求参数
        hashMap.put("startTime", startOfYesterdayStr);

        //        hashMap.put("startTime", "2022-01-01 02:32:20");
        hashMap.put("endTime", endOfYesterdayStr);
        hashMap.put("nccBaseDataEnum", i);
        hashMap.put("platformCode", "111");
        String jsonString = JSONUtil.toJsonStr(hashMap);

        // 添加请求头
        HttpResponse response = HttpUtil.createPost(basicInfoUrl).header("sourceSystem", sourceSystem).header("targetSystem", targetSystem).header("serviceName", serviceName).header("contentType", contentType).body(jsonString, "application/json").execute();
        return response;
    }
}
